package com.dsh.modbus;

import com.intelligt.modbus.jlibmodbus.Modbus;
import com.intelligt.modbus.jlibmodbus.master.ModbusMaster;
import com.intelligt.modbus.jlibmodbus.master.ModbusMasterFactory;
import com.intelligt.modbus.jlibmodbus.tcp.TcpParameters;

import java.net.InetAddress;
import java.rmi.server.ExportException;

public class app2 {

    //常量ip地址
    public static final String IP = "192.168.12.225";

    public static boolean FLAG = true;
    // 从机地址
    public static final int SLAVE_ID = 1;

    public static void main(String[] args) {

        try {
            // 设置主机参数
            TcpParameters tcpParameters = new TcpParameters();
            //设置ip地址
            InetAddress inetAddress = InetAddress.getByName(IP);
            tcpParameters.setHost(inetAddress);
            //保持活跃
            tcpParameters.setKeepAlive(true);
            //设置端口 这里 modbus 默认的端口是 502
            tcpParameters.setPort(Modbus.TCP_PORT);
            //创建主机
            ModbusMaster modbusMasterTCP = ModbusMasterFactory.createModbusMasterTCP(tcpParameters);
            Modbus.setAutoIncrementTransactionId(FLAG);


            //判断是否链接成功
            if (!modbusMasterTCP.isConnected()) {
                System.out.println("连接out");
                modbusMasterTCP.connect();
            } else {
                System.out.println("连接ok");
            }


            int offset = 0;
            int quantity = 10;
            boolean[] registers = modbusMasterTCP.readCoils(SLAVE_ID, offset, quantity);
//            for (boolean register : registers) {
////                System.out.println("读取寄存器数据 :" + offset++ + register);
//               modbusMasterTCP.writeSingleCoil(SLAVE_ID , quantity --,false );
//            }

            for (int i = 0; i < 10; i++) {
                modbusMasterTCP.writeSingleCoil(SLAVE_ID, i, true);

            }

        } catch (Exception e) {
            System.out.println(e.getClass().getName() + "---->" + e.getMessage());
            e.printStackTrace();
        }


    }
}
